package cc.messcat.dao.fupin;

import cc.messcat.common.dao.BaseDaoImpl;
import cc.messcat.entity.fupin.Family;
import cc.messcat.entity.fupin.PreventPoverty;
import cc.messcat.util.Collections;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import java.util.*;

/**
 * 2018/5/4
 */
@Repository
public class PreventPovertyDaoImpl extends BaseDaoImpl<PreventPoverty> implements PreventPovertyDao {

    @Override
    public void maintainPreventPoverty(String country, String village, String householderName, List<Family> preventPovertyFamilyList, List<Long> oldPreventFamilyID) {

        Session session = getCurrentSession();
        if(Collections.isEmpty(preventPovertyFamilyList)) {
            if(Collections.isEmpty(oldPreventFamilyID)) return;
            session.createQuery(" delete from PreventPoverty where fid in("+oldPreventFamilyID.toString().replaceAll("[\\[\\]]", "")+")").executeUpdate();
            return ;
        }

        Long pfid = preventPovertyFamilyList.get(0).getFid();
        Map<Long,String> map = new HashMap<>();

        for(Family f : preventPovertyFamilyList) {
            map.put(f.getId(),f.getName());
            session.createQuery(" update  PreventPoverty set target= :target ,householder= :householder, country=:country,amount= :amount,updateTime= :updateTime, village=:village where pfid= :pfid and fid= :fid")
                    .setParameter("pfid",pfid).setParameter("fid",f.getId()).setParameter("target",f.getName())
                    .setParameter("householder",householderName).setParameter("country",country).setParameter("village",village)
                    .setParameter("amount",f.getLastSelfExpense()).setParameter("updateTime",new Date()).executeUpdate();

            if(!oldPreventFamilyID.contains(f.getId())) {
                session.saveOrUpdate(new PreventPoverty(new Date(),new Date(),f.getFid(),f.getId(),country,village,f.getPreventType(),householderName,f.getName(),f.getLastSelfExpense()));
            }
        }

        session.createQuery(" delete from PreventPoverty where pfid= :pfid and fid not in("+map.keySet().toString().replaceAll("[\\[\\]]", "")+")")
                .setParameter("pfid",pfid).executeUpdate();

    }
}
